import { Modal, Steps, Form, Row, message, Button, Popconfirm } from 'antd';
import React, { useState, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import Step1 from './Step1';
import Step2 from './Step2';
import Step3 from './Step3';
import {
  addRoleInfo,
  updateRole as updateRoleService,
  findResourcesByRoleId,
  bindRoleUsers,
  updateRoleResources,
  findUserByRoleId,
} from '../../service';

const { confirm } = Modal;

const Add = function Add({
  visible,
  onClose,
  onSuccess,
  title = '新增角色',
  data = {},
  form,
  isEdit = false,
  lessEdit = false,
  editStep,
}) {
  const { validateFields } = form;
  const [step, setStep] = useState(editStep || 0);
  const [localLessEdit, setLocalLessEdit] = useState(lessEdit);
  const [preParams, setPreParams] = useState({ role: data });

  const { loading, run } = useRequest(values => addRoleInfo({ ...preParams, ...values }), {
    manual: true,
    onSuccess() {
      onClose();
      onSuccess();
      message.success('添加成功');
    },
  });
  const { loading: updateRoleLoading, run: updateRole } = useRequest(updateRoleService, {
    manual: true,
    onSuccess() {
      onClose();
      onSuccess();
      message.success('修改成功');
    },
  });
  const { loading: updateUserLoading, run: updateUser } = useRequest(bindRoleUsers, {
    manual: true,
    onSuccess() {
      onClose();
      onSuccess();
      message.success('修改成功');
    },
  });
  const { loading: updateSrcLoading, run: updateRoleSrc } = useRequest(updateRoleResources, {
    manual: true,
    onSuccess() {
      onClose();
      onSuccess();
      message.success('修改成功');
    },
  });

  const [checkedRoleKeys, setCheckedRoleKeys] = useState(preParams.checkedRoleKeys || []);
  const [selectUserKeys, setSelectUserKeys] = useState(preParams.userIds || []);
  const [selectUsers, setSelectUsers] = useState([]);

  const { loading: roleLoading, run: getCheckedRole } = useRequest(findResourcesByRoleId, {
    manual: true,
    onSuccess(res) {
      setCheckedRoleKeys(res);
    },
  });

  const { loading: userLoading, run: findSelectUser } = useRequest(findUserByRoleId, {
    manual: true,
    onSuccess(res) {
      setSelectUsers(res || []);
      if (res && res.length > 0) {
        const selectedKeys = selectUserKeys.concat(
          res.map(item => item.key).filter(key => selectUserKeys.every(item => item !== key)),
        );
        setSelectUserKeys(selectedKeys);
      }
    },
  });

  useEffect(() => {
    if (isEdit && step === 1) {
      getCheckedRole({ roleId: data.id });
    } else if (isEdit && step === 2) {
      findSelectUser({ roleId: data.id });
    }
  }, [isEdit, step, data.id, getCheckedRole, findSelectUser]);

  const save = useCallback(() => {
    if (selectUserKeys.length > 0) {
      setPreParams({ ...preParams, userIds: selectUserKeys });
      run({ userIds: selectUserKeys });
    } else {
      message.info('请选择用户！');
    }
  }, [run, preParams, selectUserKeys]);

  const nextStep = useCallback(() => {
    if (step === 0) {
      validateFields().then(param => {
        setPreParams({ ...preParams, role: { ...data, ...param, roleId: data.id } });
        setStep(pre => pre + 1);
      });
    } else if (step === 1) {
      if (checkedRoleKeys.length > 0) {
        setStep(pre => pre + 1);
        setPreParams({ ...preParams, resourceIds: checkedRoleKeys });
      } else {
        message.info('请选择功能权限！');
      }
    }
  }, [validateFields, preParams, step, checkedRoleKeys, data]);

  const update = useCallback(() => {
    if (step === 0) {
      validateFields().then(params => {
        if (params.competence !== data.competence) {
          confirm({
            title: '提示',
            content: '修改角色类型将影响该角色当前已选用户，是否确认修改？',
            onOk() {
              setLocalLessEdit(false);
              nextStep();
            },
            onCancel() { },
          });
        } else {
          updateRole({ id: data.id, ...params });
        }
      });
    } else if (step === 1) {
      updateRoleSrc({ roleId: data.id, resource: checkedRoleKeys });
    } else if (step === 2) {
      updateUser({ roleId: data.id, resource: selectUserKeys });
    }
  }, [
    validateFields,
    updateRole,
    data,
    step,
    updateUser,
    selectUserKeys,
    checkedRoleKeys,
    updateRoleSrc,
    nextStep,
  ]);

  const onChangeStep = useCallback(
    current => {
      if (step > current) {
        setStep(current);
      }
    },
    [step],
  );

  const formLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };

  const renderStep = function renderStep(currentStep, formInstance, initData) {
    if (currentStep === 0) {
      return <Step1 form={formInstance} data={initData.role || {}} isEdit={isEdit} formLayout={formLayout} />;
    }
    if (currentStep === 1) {
      return (
        <Step2
          loading={roleLoading}
          checkedRoleKeys={checkedRoleKeys}
          setCheckedRoleKeys={setCheckedRoleKeys}
          data={initData.role || {}}
          isEdit={isEdit}
        />
      );
    }
    return (
      <Step3
        loading={userLoading}
        targetKeys={selectUserKeys}
        setTargetKeys={setSelectUserKeys}
        selectUsers={selectUsers}
        setSelectUsers={setSelectUsers}
        data={initData.role || {}}
        isEdit={isEdit}
      />
    );
  };

  return (
    <Modal
      visible={visible}
      title={title}
      width={step === 0 ? '40%' : '80%'}
      onCancel={onClose}
      footer={
        localLessEdit
          ? [
            <Button
              key="save"
              type="primary"
              loading={updateRoleLoading || updateUserLoading || updateSrcLoading}
              onClick={update}
            >
              保存
              </Button>,
          ]
          : [
            step > 0 && (
              <Button key="pre" onClick={() => setStep(pre => pre - 1)}>
                上一步
              </Button>
            ),
            step === 2 && (
              <Popconfirm
                title={`当前还未选择任何用户，是否保存？`}
                onConfirm={() => run({ userIds: [] })}
                okText="确定"
                cancelText="取消"
              >
                <Button key="back" loading={loading}>
                  跳过
                  </Button>
              </Popconfirm>
            ),
            step === 2 && (
              <Button key="save" type="primary" loading={loading} onClick={save}>
                保存
              </Button>
            ),
            step < 2 && (
              <Button key="next" onClick={nextStep}>
                下一步
              </Button>
            ),
          ]
      }
      bodyStyle={{ minHeight: '50vh', display: 'flex', flexDirection: 'column', transition: 'all 0.5s' }}
    >
      <Row type="flex" style={{ flexDirection: 'row', alignItems: 'center' }}>
        {!localLessEdit && (
          <div style={{ borderRight: '1px solid #e2e2e2' }}>
            <Steps
              progressDot
              direction="vertical"
              labelPlacement="vertical"
              current={step}
              onChange={onChangeStep}
              style={{ marginBottom: 24 }}
            >
              <Steps.Step title="基本信息" description={<div style={{ height: 60 }} />} />
              <Steps.Step title="功能权限" description={<div style={{ height: 60 }} />} />
              <Steps.Step title="分配用户" />
            </Steps>
          </div>
        )}
        <Row justify="center" type="flex" align="middle" style={{ flex: 1 }}>
          <Form style={isEdit ? { flex: 1 } : { flex: 1, marginTop: -10 }} {...formLayout}>
            {renderStep(step, form, preParams)}
          </Form>
        </Row>
      </Row>
    </Modal>
  );
};

export default Form.create()(Add);
